Page({
  data: {
    words: [],
  },

  onLoad() {
    this.loadWordsList();
  },
  goTo: function(e) {
    getApp().globalData.currentWord = this.data.words[e.currentTarget.dataset.index];
    wx.navigateTo({url: '/pages/detail/detail'});
  },
  removeDuplicates: function(words) {
    const seen = new Set();
    return words.filter(word => {
        const duplicate = seen.has(word.wordId);
        seen.add(word.wordId);
        return !duplicate;
    });
  },
  removeWord:function(e){
    wx.request({
      url: `http://81.70.199.174:8081/word/remove?wordId=${this.data.words[e.currentTarget.dataset.index].wordId}`,
      method:'DELETE',
      header:{
        'Authorization':getApp().globalData.token,
      },
      success:(res)=>{
        if(res.data.code===200){
          wx.showToast({
            title: '移除成功',
            icon:'success',
            duration:1000
          });
          wx.request({
            url: `http://81.70.199.174:8081/user/updateProgress?addWords=${this.data.words.length}`,
            method:'PATCH',
            header:{
              'Authorization':getApp().globalData.token,
            },

            success:(res)=>{
              console.log("更新进度成功");
            },fail:(res)=>{
              console.log("失败");
            }
          });
        }else{
          wx.showToast({
            title: '移除成功',
            icon:'success',
            duration:1000
          });
        }
        this.loadWordsList();
      },fail: (err) => {
        wx.showToast({
            title: '网络错误',
            icon: 'none',
            duration: 1000
        });
      }
    })
  },
  loadWordsList:function(){
    wx.request({
      url: 'http://81.70.199.174:8081/word/getOld',
      method:'GET',
      header:{
        'Authorization':getApp().globalData.token,
      },
      success:(res)=>{
        console.log(res);
        if(res.data.code===200){
          this.setData({
            words:this.removeDuplicates(res.data.data),
          })
        }
      },
    });
  },
});